import GCDWebServers
import UIKit
import Network
import CoreImage.CIFilterBuiltins
import QuickLook

@available(iOS 8.2, *)
class ViewController: UIViewController {
  @IBOutlet var statusLabel: UILabel?
  @IBOutlet var startButton: UIButton?
  @IBOutlet var guideButton: UIButton?
  
  var webServer: GCDWebUploader!
  var isServerRunning: Bool = false

  override func viewDidLoad() {
    super.viewDidLoad()
    setupUI()
  }
  
  private func setupUI() {
    // 设置简洁的背景色
    view.backgroundColor = UIColor.white
    
    title = "文件传输服务器"
    
    // 设置导航栏样式
    if #available(iOS 13.0, *) {
      navigationController?.navigationBar.prefersLargeTitles = true
      navigationController?.navigationBar.largeTitleTextAttributes = [
        .foregroundColor: UIColor.label,
        .font: UIFont.systemFont(ofSize: 32, weight: .bold)
      ]
    }
    
    setupStatusLabel()
    setupStartButton()
    setupGuideButton()
  }
  
  private func setupStatusLabel() {
    guard let statusLabel = statusLabel else { return }
    
    statusLabel.text = "🔴 服务器已停止"
    statusLabel.textColor = UIColor.red
    statusLabel.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
    statusLabel.textAlignment = .center
    statusLabel.numberOfLines = 0
  }
  
  private func setupStartButton() {
    guard let startButton = startButton else { return }
    
    startButton.setTitle("🚀 启动服务器", for: .normal)
    startButton.setTitleColor(.white, for: .normal)
    startButton.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .bold)
    startButton.backgroundColor = UIColor(red: 0.2, green: 0.78, blue: 0.35, alpha: 1.0)
    
    startButton.layer.cornerRadius = 15
    startButton.layer.shadowColor = UIColor.black.cgColor
    startButton.layer.shadowOffset = CGSize(width: 0, height: 2)
    startButton.layer.shadowRadius = 4
    startButton.layer.shadowOpacity = 0.2
  }
  
  private func setupGuideButton() {
    guard let guideButton = guideButton else { return }
    
    guideButton.setTitle("📖 查看使用指导", for: .normal)
    guideButton.setTitleColor(.white, for: .normal)
    guideButton.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .bold)
    guideButton.backgroundColor = UIColor(red: 0.0, green: 0.48, blue: 1.0, alpha: 1.0)
    
    guideButton.layer.cornerRadius = 15
    guideButton.layer.shadowColor = UIColor.black.cgColor
    guideButton.layer.shadowOffset = CGSize(width: 0, height: 2)
    guideButton.layer.shadowRadius = 4
    guideButton.layer.shadowOpacity = 0.2
    guideButton.isEnabled = false
    guideButton.alpha = 0.6
  }

  @IBAction func startButtonTapped(_ sender: UIButton) {
    if isServerRunning {
      stopServer()
    } else {
      startServer()
    }
  }
  
  @IBAction func guideButtonTapped(_ sender: UIButton) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    if let guideVC = storyboard.instantiateViewController(withIdentifier: "GuideViewController") as? GuideViewController {
      guideVC.updateServerStatus(isRunning: isServerRunning, port: webServer?.port ?? 0)
      navigationController?.pushViewController(guideVC, animated: true)
    }
  }
  
  private func startServer() {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    webServer = GCDWebUploader(uploadDirectory: documentsPath)
    webServer.delegate = self
    webServer.allowHiddenItems = true
    
    if webServer.start() {
      isServerRunning = true
      updateUIForServerRunning()
      
      // 显示成功提示
      showAlert(
        title: "🎉 服务器启动成功",
        message: "现在可以通过电脑浏览器访问文件上传页面了！\n\n点击\"查看使用指导\"了解详细使用方法。"
      )
    } else {
      updateUIForServerStopped()
      showAlert(
        title: "❌ 启动失败",
        message: "无法启动服务器，请检查网络设置或重试。"
      )
    }
  }
  
  private func stopServer() {
    webServer?.stop()
    webServer = nil
    isServerRunning = false
    updateUIForServerStopped()
  }
  
  private func updateUIForServerRunning() {
    guard let statusLabel = statusLabel,
          let startButton = startButton,
          let guideButton = guideButton else { return }
    
    // 更新状态标签
    statusLabel.text = "🟢 服务器运行中 - 端口: \(webServer.port)"
    statusLabel.textColor = UIColor(red: 0.2, green: 0.78, blue: 0.35, alpha: 1.0)
    
    // 更新启动按钮
    startButton.setTitle("🛑 停止服务器", for: .normal)
    startButton.backgroundColor = UIColor.red
    
    // 启用指导按钮
    guideButton.isEnabled = true
    UIView.animate(withDuration: 0.3) {
      guideButton.alpha = 1.0
    }
  }
  
  private func updateUIForServerStopped() {
    guard let statusLabel = statusLabel,
          let startButton = startButton,
          let guideButton = guideButton else { return }
    
    // 更新状态标签
    statusLabel.text = "🔴 服务器已停止"
    statusLabel.textColor = UIColor.red
    
    // 更新启动按钮
    startButton.setTitle("🚀 启动服务器", for: .normal)
    startButton.backgroundColor = UIColor(red: 0.2, green: 0.78, blue: 0.35, alpha: 1.0)
    
    // 禁用指导按钮
    guideButton.isEnabled = false
    UIView.animate(withDuration: 0.3) {
      guideButton.alpha = 0.6
    }
  }
  
  private func showAlert(title: String, message: String) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "确定", style: .default))
    present(alert, animated: true)
  }

  override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    if isMovingFromParent {
      stopServer()
    }
  }
}

extension ViewController: GCDWebUploaderDelegate {
  func webUploader(_ uploader: GCDWebUploader, didUploadFileAtPath path: String) {
    print("文件上传成功: \(path)")
  }
  
  func webUploader(_ uploader: GCDWebUploader, didMoveItemFromPath fromPath: String, toPath: String) {
    print("文件移动: \(fromPath) -> \(toPath)")
  }
  
  func webUploader(_ uploader: GCDWebUploader, didDeleteItemAtPath path: String) {
    print("文件删除: \(path)")
  }
  
  func webUploader(_ uploader: GCDWebUploader, didCreateDirectoryAtPath path: String) {
    print("创建目录: \(path)")
  }
}

// GuideViewController 类
class GuideViewController: UIViewController {
  @IBOutlet var titleLabel: UILabel?
  @IBOutlet var statusLabel: UILabel?
  @IBOutlet var ipAddressLabel: UILabel?
  @IBOutlet var portLabel: UILabel?
  @IBOutlet var qrCodeImageView: UIImageView?
  @IBOutlet var instructionTextView: UITextView?
  @IBOutlet var viewFilesButton: UIButton?
  
  private var isServerRunning = false
  private var serverPort: UInt = 0
  
  // 文件列表数据
  private var fileList: [String] = []
  private var filePaths: [String] = []
  private var selectedFileURL: URL?
  
  override func viewDidLoad() {
    super.viewDidLoad()
    setupUI()
    updateServerInfo()
  }
  
  private func setupUI() {
    // 设置简洁的背景色
    view.backgroundColor = UIColor.white
    
    title = "使用指导"
    
    setupLabels()
    setupQRCode()
    setupInstructionText()
    setupViewFilesButton()
  }
  
  private func setupLabels() {
    // 设置标题标签
    if let titleLabel = titleLabel {
      titleLabel.font = UIFont.systemFont(ofSize: 24, weight: .bold)
      titleLabel.textAlignment = .center
      titleLabel.textColor = UIColor.black
    }
    
    // 设置状态标签
    if let statusLabel = statusLabel {
      statusLabel.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
      statusLabel.textAlignment = .center
    }
    
    // 设置IP和端口标签
    if let ipLabel = ipAddressLabel {
      ipLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
      ipLabel.textAlignment = .center
      ipLabel.textColor = UIColor.black
    }
    
    if let portLabel = portLabel {
      portLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
      portLabel.textAlignment = .center
      portLabel.textColor = UIColor.black
    }
  }
  
  private func setupQRCode() {
    guard let qrImageView = qrCodeImageView else { return }
    qrImageView.backgroundColor = UIColor.white
    qrImageView.layer.cornerRadius = 10
    qrImageView.layer.borderWidth = 1
    qrImageView.layer.borderColor = UIColor.lightGray.cgColor
  }
  
  private func setupInstructionText() {
    guard let textView = instructionTextView else { return }
    
    textView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
    textView.textColor = UIColor.black
    
    textView.layer.cornerRadius = 10
    textView.font = UIFont.systemFont(ofSize: 16)
    textView.isEditable = false
    textView.isScrollEnabled = true
    
    textView.text = """
📋 使用说明：

方法一：扫描二维码
• 使用电脑或其他设备扫描上方二维码
• 直接访问文件上传页面

方法二：手动输入地址
• 确保电脑与手机连接同一WiFi网络
• 在电脑浏览器中输入上述地址
• 进入文件上传界面

📁 功能说明：
• 上传文件到手机
• 下载手机中的文件
• 创建和删除文件夹
• 重命名文件和文件夹
"""
  }
  
  private func setupViewFilesButton() {
    guard let button = viewFilesButton else { return }
    
    button.setTitle("📁 查看已上传文件", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .bold)
    button.backgroundColor = UIColor(red: 0.0, green: 0.48, blue: 1.0, alpha: 1.0)
    
    button.layer.cornerRadius = 15
    button.layer.shadowColor = UIColor.black.cgColor
    button.layer.shadowOffset = CGSize(width: 0, height: 2)
    button.layer.shadowRadius = 4
    button.layer.shadowOpacity = 0.2
  }
  
  func updateServerStatus(isRunning: Bool, port: UInt) {
    isServerRunning = isRunning
    serverPort = port
    
    if isViewLoaded {
      updateServerInfo()
    }
  }
  
  private func updateServerInfo() {
    guard let statusLabel = statusLabel,
          let ipLabel = ipAddressLabel,
          let portLabel = portLabel else { return }
    
    if isServerRunning {
      statusLabel.text = "✅ 服务器运行中"
      statusLabel.textColor = UIColor(red: 0.2, green: 0.78, blue: 0.35, alpha: 1.0)
      
      let ipAddress = getWiFiAddress() ?? "未连接WiFi"
      ipLabel.text = "IP地址: \(ipAddress)"
      portLabel.text = "端口: \(serverPort)"
      
      // 生成二维码
      if ipAddress != "未连接WiFi" {
        let urlString = "http://\(ipAddress):\(serverPort)"
        generateQRCode(from: urlString)
      }
    } else {
      statusLabel.text = "❌ 服务器未运行"
      statusLabel.textColor = UIColor.red
      ipLabel.text = "请先启动服务器"
      portLabel.text = ""
      qrCodeImageView?.image = nil
    }
  }
  
  private func getWiFiAddress() -> String? {
    var address: String?
    var ifaddr: UnsafeMutablePointer<ifaddrs>?
    
    guard getifaddrs(&ifaddr) == 0 else { return nil }
    guard let firstAddr = ifaddr else { return nil }
    
    for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
      let interface = ifptr.pointee
      let addrFamily = interface.ifa_addr.pointee.sa_family
      
      if addrFamily == UInt8(AF_INET) {
        let name = String(cString: interface.ifa_name)
        if name == "en0" {
          var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
          getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len),
                     &hostname, socklen_t(hostname.count),
                     nil, socklen_t(0), NI_NUMERICHOST)
          address = String(cString: hostname)
        }
      }
    }
    
    freeifaddrs(ifaddr)
    return address
  }
  
  private func generateQRCode(from string: String) {
    guard let qrImageView = qrCodeImageView else { return }
    
    let data = string.data(using: String.Encoding.ascii)
    
    if let filter = CIFilter(name: "CIQRCodeGenerator") {
      filter.setValue(data, forKey: "inputMessage")
      let transform = CGAffineTransform(scaleX: 3, y: 3)
      
      if let output = filter.outputImage?.transformed(by: transform) {
        let context = CIContext()
        if let cgImage = context.createCGImage(output, from: output.extent) {
          qrImageView.image = UIImage(cgImage: cgImage)
        }
      }
    }
  }
  
  private func showAlert(title: String, message: String) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "确定", style: .default))
    present(alert, animated: true)
  }
  
  @IBAction func viewFilesButtonTapped(_ sender: UIButton) {
    // 直接使用文件管理器获取文档目录中的文件
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    let fileManager = FileManager.default
    
    do {
      // 创建文件列表视图控制器
      let fileListVC = UIViewController()
      fileListVC.title = "已上传文件"
      fileListVC.view.backgroundColor = UIColor.white
      
      // 创建表视图
      let tableView = UITableView(frame: fileListVC.view.bounds, style: .plain)
      tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
      tableView.delegate = self
      tableView.dataSource = self
      fileListVC.view.addSubview(tableView)
      
      // 获取文件列表
      self.fileList = try fileManager.contentsOfDirectory(atPath: documentsPath)
        .filter { !$0.hasPrefix(".") } // 过滤隐藏文件
      self.filePaths = self.fileList.map { documentsPath + "/" + $0 }
      
      // 显示文件列表
      navigationController?.pushViewController(fileListVC, animated: true)
      
    } catch {
      showAlert(title: "❌ 错误", message: "无法访问文件列表: \(error.localizedDescription)")
    }
  }
}

// 为GuideViewController添加表视图协议
extension GuideViewController: UITableViewDelegate, UITableViewDataSource {
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return fileList.count
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cellIdentifier = "FileCell"
    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) 
      ?? UITableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier)
    
    let fileName = fileList[indexPath.row]
    cell.textLabel?.text = fileName
    
    // 获取文件属性
    if let attributes = try? FileManager.default.attributesOfItem(atPath: filePaths[indexPath.row]) {
      if let size = attributes[.size] as? NSNumber {
        let formatter = ByteCountFormatter()
        formatter.allowedUnits = [.useAll]
        formatter.countStyle = .file
        let sizeString = formatter.string(fromByteCount: size.int64Value)
        cell.detailTextLabel?.text = sizeString
      }
    }
    
    // 设置文件图标
    let fileExtension = (fileName as NSString).pathExtension.lowercased()
    var fileImage: UIImage?
    
    switch fileExtension {
    case "jpg", "jpeg", "png", "gif":
      fileImage = UIImage(named: "photo")
    case "pdf":
      fileImage = UIImage(named: "pdf")
    case "doc", "docx":
      fileImage = UIImage(named: "document")
    case "xls", "xlsx":
      fileImage = UIImage(named: "spreadsheet")
    case "zip", "rar":
      fileImage = UIImage(named: "archive")
    default:
      fileImage = UIImage(named: "file")
    }
    
    // 使用默认图标如果找不到自定义图标
    if fileImage == nil {
      if #available(iOS 13.0, *) {
        fileImage = UIImage(systemName: "doc")
      }
    }
    
    cell.imageView?.image = fileImage
    
    return cell
  }
  
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
    
    // 预览文件
    let filePath = filePaths[indexPath.row]
    let fileURL = URL(fileURLWithPath: filePath)
    
    // 使用QuickLook预览文件
    let previewController = QLPreviewController()
    previewController.dataSource = self
    self.selectedFileURL = fileURL
    navigationController?.pushViewController(previewController, animated: true)
  }
  
  // 删除文件
  func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
      let filePath = filePaths[indexPath.row]
      
      do {
        try FileManager.default.removeItem(atPath: filePath)
        fileList.remove(at: indexPath.row)
        filePaths.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
      } catch {
        showAlert(title: "❌ 删除失败", message: "无法删除文件: \(error.localizedDescription)")
      }
    }
  }
  
  func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
    return "删除"
  }
}

// 添加QuickLook预览支持
extension GuideViewController: QLPreviewControllerDataSource {
  func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
    return selectedFileURL != nil ? 1 : 0
  }
  
  func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
    return selectedFileURL! as QLPreviewItem
  }
}
